package sunwin.yois.web.uiservice;

import jodd.datetime.JDateTime;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sunwin.yois.web.model.*;
import sunwin.yoms.comm.YomsException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * Created by liangzizheng on 2015/8/25.
 */
public class WeatherService {
    public static WeatherService Instance = new WeatherService();
    private final String urlStirng = "http://wthrcdn.etouch.cn/WeatherApi?city=";

    private WeatherService() {

    }

    public WeatherDomain getWeatherInformation(String cityName) throws Exception {

        String param= URLEncoder.encode(cityName,"UTF-8");            // URLEncoder
//        URL localURL = new URL(urlStirng + "%E5%8D%97%E4%BA%AC");
        URL localURL = new URL(urlStirng + param);                    // URL
        URLConnection connection = localURL.openConnection();         // URLConnection

        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;  //HttpURLConnection
        InputStream inputStream = null;
        GZIPInputStream inputStreamReader = null;                   //GZIPInputStream

        if (httpURLConnection.getResponseCode() >= 300) {
            throw new YomsException("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new GZIPInputStream(inputStream);
            byte[] result = readStream(inputStreamReader);
            String stringResult = new String(result,"UTF-8");
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringResult.getBytes("UTF-8"));
            return createWeatherDomain(byteArrayInputStream);
        } catch (YomsException e) {
            return null;
        } finally {

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }
    }

    /**
     * 读取流
     *
     * @param inStream
     * @return 字节数组
     * @throws Exception
     */
    private byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();        // ByteArrayOutputStream
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

    private WeatherDomain createWeatherDomain(ByteArrayInputStream weatherXml) throws DocumentException {

        SAXReader reader = new SAXReader();
        Document document = reader.read(weatherXml);      //读取XML文件,获得document对象
        Element root = document.getRootElement();

        WeatherDomain weatherDomain = new WeatherDomain();
        Element environment = root.element("environment");
        Element yesterday = root.element("yesterday");
        Element forecast = root.element("forecast");
        Element zhishus = root.element("zhishus");


        Element cityEle = root.element("city");
        if(cityEle==null){                          //  先判断xml文件中城市名是否存在
            weatherDomain = setWeatherDefault();
            return weatherDomain;
        }
        String city = cityEle.getText();           // 先读取  再赋值
        weatherDomain.setCity(city);
        String updatetime = root.element("updatetime").getText();
        weatherDomain.setUpdateTime(updatetime);
        String wendu = root.element("wendu").getText();
        weatherDomain.setWendu(wendu);
        String fengli = root.element("fengli").getText();
        weatherDomain.setFengli(fengli);
        String shidu = root.element("shidu").getText();
        weatherDomain.setShidu(shidu);
        String fengxiang = root.element("fengxiang").getText();
        weatherDomain.setFengxiang(fengxiang);
        String sunrise_1 = root.element("sunrise_1").getText();
        weatherDomain.setSunrise(sunrise_1);
        String sunset_1 = root.element("sunset_1").getText();
        weatherDomain.setSunset(sunset_1);

        String aqi = environment.element("aqi").getText();
        weatherDomain.getEnvironmentDomain().setAqi(aqi);
        String pm25 = environment.element("pm25").getText();
        weatherDomain.getEnvironmentDomain().setPm25(pm25);
        String suggest = environment.element("suggest").getText();
        weatherDomain.getEnvironmentDomain().setSuggest(suggest);
        String quality = environment.element("quality").getText();
        weatherDomain.getEnvironmentDomain().setQuality(quality);
        String majorPollutants = environment.element("MajorPollutants").getText();
        weatherDomain.getEnvironmentDomain().setMajorPollutants(majorPollutants);
        String o3 = environment.element("o3").getText();
        weatherDomain.getEnvironmentDomain().setO3(o3);
        String co = environment.element("co").getText();
        weatherDomain.getEnvironmentDomain().setCo(co);
        String pm10 = environment.element("pm10").getText();
        weatherDomain.getEnvironmentDomain().setPm10(pm10);
        String so2 = environment.element("so2").getText();
        weatherDomain.getEnvironmentDomain().setSo2(so2);
        String no2 = environment.element("no2").getText();
        weatherDomain.getEnvironmentDomain().setNo2(no2);
        String time = environment.element("time").getText();
        weatherDomain.getEnvironmentDomain().setTime(time);

        Element alarmele = root.element("alarm");
        if (alarmele != null) {                                    // 同样是先判断
            String citykey = alarmele.element("cityKey").getText();
            weatherDomain.getWeatherAlarmDomain().setCityKey(citykey);
            String cityName = alarmele.elementText("cityName");
            weatherDomain.getWeatherAlarmDomain().setCityName(cityName);
            String alarmType = alarmele.elementText("alarmType");
            weatherDomain.getWeatherAlarmDomain().setAlarmType(alarmType);
            String alarmDegree = alarmele.elementText("alarmDegree");
            weatherDomain.getWeatherAlarmDomain().setAlarmDegree(alarmDegree);
            String alarmText = alarmele.elementText("alarmText");
            weatherDomain.getWeatherAlarmDomain().setAlarmText(alarmText);
            String alarmDetail = alarmele.elementText("alarm_details");
            weatherDomain.getWeatherAlarmDomain().setAlarmDetail(alarmDetail);
            String standard = alarmele.elementText("standard");
            weatherDomain.getWeatherAlarmDomain().setStandard(standard);
            String alarmSuggest = alarmele.elementText("suggest");
            weatherDomain.getWeatherAlarmDomain().setAlarmSuggest(alarmSuggest);
            String alarmImgurl = alarmele.elementText("imgUrl");
            weatherDomain.getWeatherAlarmDomain().setAlarmImgUrl(alarmImgurl);
            String alarmTime = alarmele.elementText("time");
            weatherDomain.getWeatherAlarmDomain().setAlarmTime(alarmTime);
        }

        WeatherDateDomain weatherDateDomainYesterday = new WeatherDateDomain();

        String date_1 = yesterday.element("date_1").getText();
        weatherDateDomainYesterday.setDate(date_1);
        String high_1 = yesterday.element("high_1").getText();
        weatherDateDomainYesterday.setHighWendu(high_1);
        String low_1 = yesterday.element("low_1").getText();
        weatherDateDomainYesterday.setLowWendu(low_1);
        Element day_1 = yesterday.element("day_1");

        String dtype_1 = day_1.element("type_1").getText();
        weatherDateDomainYesterday.getDay().setType(dtype_1);
        String dfx_1 = day_1.element("fx_1").getText();
        weatherDateDomainYesterday.getDay().setFengxiang(dfx_1);
        String dfl_1 = day_1.element("fl_1").getText();
        weatherDateDomainYesterday.getDay().setFengli(dfl_1);
        Element night_1 = yesterday.element("night_1");
        String ntype_1 = night_1.element("type_1").getText();
        weatherDateDomainYesterday.getNight().setType(ntype_1);
        String nfx_1 = night_1.element("fx_1").getText();
        weatherDateDomainYesterday.getNight().setFengxiang(nfx_1);
        String nfl_1 = night_1.element("fl_1").getText();
        weatherDateDomainYesterday.getNight().setFengli(nfl_1);
        weatherDomain.getWeatherDateDomains().add(weatherDateDomainYesterday);

        JDateTime jDateTime = new JDateTime();
        jDateTime.setCurrentTime();
        for (Iterator i = forecast.elementIterator(); i.hasNext(); ) {
            Element weather = (Element) i.next();
            WeatherDateDomain weatherDateDomain = new WeatherDateDomain();

            String tempdate = weather.element("date").getText();
            String date = jDateTime.getMonth()+"月"+ tempdate.substring(0,tempdate.indexOf("星")-1)+"号";

            weatherDateDomain.setYue(String.valueOf(jDateTime.getMonth()));
            weatherDateDomain.setRi(String.valueOf(jDateTime.getDay()));

            weatherDateDomain.setDate(date);
            weatherDateDomain.setWeekDay(tempdate.substring(tempdate.indexOf("星")));

            weatherDateDomain.setXingqiji(tempdate.substring(tempdate.indexOf("期") + 1));

            String high = weather.element("high").getText();
            String[] wenHight = high.split(" ");
            weatherDateDomain.setHighWendu(wenHight[1].replace("℃",""));     // change this
            String low = weather.element("low").getText();
            String[] wenLow = low.split(" ");
            String tempLowWendu = wenLow[1].replace("℃", "");
            weatherDateDomain.setLowWendu(tempLowWendu);

            Element day = weather.element("day");
            String dtype = day.element("type").getText();
            weatherDateDomain.getDay().setType(dtype);
            weatherDateDomain.getDay().setImageUrl(getWeatherImage(dtype));
            String dfengxiang = day.element("fengxiang").getText();
            weatherDateDomain.getDay().setFengxiang(dfengxiang);
            String dfengli = day.element("fengli").getText();
            weatherDateDomain.getDay().setFengli(dfengli);

            Element night = weather.element("night");
            String ntype = night.element("type").getText();
            weatherDateDomain.getNight().setType(ntype);
            weatherDateDomain.getNight().setImageUrl(getWeatherImage(dtype));
            String nfengxiang = night.element("fengxiang").getText();
            weatherDateDomain.getNight().setFengxiang(nfengxiang);
            String nfengli = night.element("fengli").getText();
            weatherDateDomain.getNight().setFengli(nfengli);
            weatherDomain.getWeatherDateDomains().add(weatherDateDomain);
            jDateTime.addDay(1);
        }
        for (Iterator i = zhishus.elementIterator(); i.hasNext(); ) {
            Element zhishu = (Element) i.next();
            WeatherNoticeDomain weatherNoticeDomain = new WeatherNoticeDomain();
            String name = zhishu.element("name").getText();
            weatherNoticeDomain.setName(name);
            String value = zhishu.element("value").getText();
            weatherNoticeDomain.setValue(value);
            String detail = zhishu.element("detail").getText();
            weatherNoticeDomain.setDetail(detail);
            weatherDomain.getWeatherNotices().add(weatherNoticeDomain);
        }
        return weatherDomain;
    }

    private WeatherDomain setWeatherDefault(){
        WeatherDomain weatherDomain = new WeatherDomain();
        weatherDomain.setCity("无");
        weatherDomain.setSunset("0");
        weatherDomain.setSunrise("0");
        weatherDomain.setFengxiang("无");
        weatherDomain.setFengli("无");
        weatherDomain.setShidu("无");
        weatherDomain.setUpdateTime("无");
        weatherDomain.setWendu("0");

        EnvironmentDomain environmentDomain=new EnvironmentDomain();
        environmentDomain.setAqi("0");
        environmentDomain.setTime("无");
        environmentDomain.setNo2("0");
        environmentDomain.setSo2("0");
        environmentDomain.setCo("0");
        environmentDomain.setMajorPollutants("无");
        environmentDomain.setO3("0");
        environmentDomain.setPm10("0");
        environmentDomain.setPm25("0");
        environmentDomain.setQuality("无");
        environmentDomain.setSuggest("无");

        weatherDomain.setEnvironmentDomain(environmentDomain);

        WeatherAlarmDomain weatherAlarmDomain = new WeatherAlarmDomain();
        weatherAlarmDomain.setAlarmTime("无");
        weatherAlarmDomain.setAlarmImgUrl("无");
        weatherAlarmDomain.setAlarmSuggest("无");
        weatherAlarmDomain.setStandard("无");
        weatherAlarmDomain.setAlarmDegree("无");
        weatherAlarmDomain.setAlarmDetail("无");
        weatherAlarmDomain.setAlarmText("无");
        weatherAlarmDomain.setAlarmType("无");
        weatherAlarmDomain.setCityName("无");
        weatherAlarmDomain.setCityKey("无");
        weatherDomain.setWeatherAlarmDomain(weatherAlarmDomain);
        List<WeatherDateDomain> weatherDateDomains=new ArrayList<>();
        JDateTime jDateTime = new JDateTime();
        jDateTime.setCurrentTime();
        jDateTime.subDay(1);
        for (int i = 0; i < 4; i++) {
            WeatherDateDomain weatherDateDomain=new WeatherDateDomain();
            weatherDateDomain.setXingqiji(getWeekDay(jDateTime.getDayOfWeek()));
            weatherDateDomain.setRi(String.valueOf(jDateTime.getDay()));
            weatherDateDomain.setYue(String.valueOf(jDateTime.getMonth()));
            weatherDateDomain.setWeekDay("无");
            weatherDateDomain.setDate("无");
            WeatherInfoDomain weatherInfoDomainDay=new WeatherInfoDomain();
            weatherInfoDomainDay.setFengli("无");
            weatherInfoDomainDay.setImageUrl("weather1");
            weatherInfoDomainDay.setFengxiang("无");
            weatherInfoDomainDay.setType("无");
            weatherDateDomain.setDay(weatherInfoDomainDay);
            weatherDateDomain.setHighWendu("无");
            weatherDateDomain.setLowWendu("无");
            weatherDateDomain.setNight(weatherInfoDomainDay);
            jDateTime.addDay(1);
            weatherDateDomains.add(weatherDateDomain);
        }
        weatherDomain.setWeatherDateDomains(weatherDateDomains);

        List<WeatherNoticeDomain> weatherNoticeDomains = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            WeatherNoticeDomain weatherNoticeDomain = new WeatherNoticeDomain();
            weatherNoticeDomain.setDetail("无");
            weatherNoticeDomain.setValue("无");
            weatherNoticeDomain.setName("无");
            weatherNoticeDomains.add(weatherNoticeDomain);
        }
        weatherDomain.setWeatherNotices(weatherNoticeDomains);

        return weatherDomain;
    }

    private String getWeekDay(int day){
        String weekDay="";
        switch (day){
            case 1:
                weekDay="一";
                break;
            case 2:
                weekDay="二";
                break;
            case 3:
                weekDay="三";
                break;
            case 4:
                weekDay="四";
                break;
            case 5:
                weekDay="五";
                break;
            case 6:
                weekDay="六";
                break;
            case 7:
                weekDay="日";
                break;
        }
        return weekDay;
    }

    private String getWeatherImage(String weatherType){   // url 获取图片
        String imgUrl="";
        switch (weatherType){
            case "晴":imgUrl+="weather1";break;
            case "多云":imgUrl+="weather2";break;
            case "阴":imgUrl+="weather3";break;
            case "阵雨":imgUrl+="weather4";break;
            case "雷阵雨":imgUrl+="weather5";break;
            case "雷阵雨伴有冰雹":imgUrl+="weather6";break;
            case "雨夹雪":imgUrl+="weather7";break;
            case "小雨":imgUrl+="weather8";break;
            case "中雨":imgUrl+="weather9";break;
            case "大雨":imgUrl+="weather10";break;
            case "暴雨":imgUrl+="weather11";break;
            case "大暴雨":imgUrl+="weather12";break;
            case "特大暴雨":imgUrl+="weather13";break;
            case "陈雪":imgUrl+="weather14";break;
            case "小雪":imgUrl+="weather15";break;
            case "中雪":imgUrl+="weather16";break;
            case "大雪":imgUrl+="weather17";break;
            case "暴雪":imgUrl+="weather18";break;
            case "雾":imgUrl+="weather19";break;
            case "冻雨":imgUrl+="weather20";break;
            case "沙尘暴":imgUrl+="weather21";break;
            case "小到中雨":imgUrl+="weather22";break;
            case "中到大雨":imgUrl+="weather23";break;
            case "大到暴雨":imgUrl+="weather24";break;
            case "暴雨到大暴雨":imgUrl+="weather25";break;
            case "大到特大暴雨":imgUrl+="weather26";break;
            case "小到中雪":imgUrl+="weather27";break;
            case "中到大雪":imgUrl+="weather28";break;
            case "大到暴雪":imgUrl+="weather29";break;
            case "浮尘":imgUrl+="weather30";break;
            case "扬沙":imgUrl+="weather31";break;
            case "强沙尘暴":imgUrl+="weather32";break;
            case "霾":imgUrl+="weather33";break;
        }
        return imgUrl;
    }
}
